"""
    数据库操作
"""
import json

import pymysql

from zonghe.caw import file_reader


def connect(db_info):
    """
    建立数据库连接
    :param db_info: 数据库信息
    :return: 数据库连接
    """
    try:
        r = pymysql.connect(user=db_info["user"],
                            password=db_info["pwd"],
                            host=db_info["host"],
                            port=db_info["port"],
                            database=db_info["name"],
                            charset='utf8')
        print("连接数据库成功")
        return r
    except Exception as e:
        print("连接数据库异常", e)


def execute(conn, sql):
    """
    执行sql语句
    :param conn: 数据库连接
    :param sql: sql语句
    :return:
    """
    try:
        # 获取游标
        cursor = conn.cursor()
        cursor.execute(sql)
        conn.commit()  # 提交
        r = cursor.fetchall()
        print("执行SQL语句", sql, "成功")
        return r
    except Exception as e:
        print("执行SQL语句", sql, "失败，异常信息为", e)

def dis_connect(conn):
    """

    :param conn:
    :return:
    """
    try:
        conn.close()
        print("断开数据库连接成功")
    except Exception as e:
        print("断开数据库连接失败",e)
if __name__ == '__main__':
    # test.ini读出来的是字符串，要转成json格式才可以使用
    s = json.loads(file_reader.read_config("db_info"))
    r = connect(s)
    ret = execute(r, "select * from member where  mobilephone like '1801234561%'")
    print(ret)
    ret = execute(r, "delete from member where mobilephone like '1801234561%'")
    print(ret)
    ret = execute(r, "select * from member where mobilephone like '1801234561%'")
    print(ret)
